from django.db import models
from django.db.models import Q
from datetime import timedelta, datetime, date
from illness_protection.models import ImportantArea,ImportantCity
import time


def cal_time(date1,date2):
    # %Y-%m-%d为日期格式，其中的-可以用其他代替或者不写，但是要统一，同理后面的时分秒也一样；可以只计算日期，不计算时间。
    date1 = time.strptime(date1, "%Y-%m-%d")
    date2 = time.strptime(date2, "%Y-%m-%d")

    # 根据上面需要计算日期还是日期时间，来确定需要几个数组段。下标0表示年，小标1表示月，依次类推...
    date1 = datetime(date1[0], date1[1], date1[2])
    date2 = datetime(date2[0], date2[1], date2[2])
    # 返回两个变量相差的值，就是相差天数
    # print((date2-date1).days)#将天数转成int型
    return (date2 - date1).days


class ProvinceCityNew(models.Model):
    name = models.CharField(max_length=255, blank=True, null=True)
    short_name = models.CharField(max_length=255, blank=True, null=True)
    id = models.IntegerField(primary_key=True)
    pid = models.IntegerField(blank=True, null=True)
    level = models.IntegerField(blank=True, null=True)
    order = models.IntegerField()

    class Meta:
        managed = False
        db_table = 'province_city_new'

    def __str__(self):
        return self.name

    def __repr__(self):
        return self.name


class PeopleAtSchool(models.Model):
    class Meta:
        managed = False
        db_table = 'people_at_school_new'
        verbose_name = '一日一报'
        verbose_name_plural = '一日一报'

    xm = models.CharField(max_length=255)
    xh = models.CharField(max_length=255, primary_key=True)
    yxdm = models.CharField(max_length=255)
    bjdm = models.CharField(max_length=255)
    type = models.CharField(max_length=255)


class ReturnSchoolQuestionnaire(models.Model):
    class Meta:
        managed = False
        app_label = 'ibps_business'
        db_table = 't_xsfxxxdc'
        verbose_name = '学生返校信息调查'
        verbose_name_plural = '学生返校信息调查'

    id = models.CharField(db_column='id_', primary_key=True, max_length=64)
    tenant_id = models.CharField(db_column='tenant_id_', max_length=64, blank=True, null=True)
    ip = models.CharField(db_column='ip_', max_length=15, blank=True, null=True)
    create_by = models.CharField(db_column='create_by_', max_length=64, blank=True, null=True)
    create_time = models.DateTimeField(db_column='create_time_', blank=True, null=True)
    update_by = models.CharField(db_column='update_by_', max_length=64, blank=True, null=True)
    update_time = models.DateTimeField(db_column='update_time_', blank=True, null=True)
    name = models.CharField(db_column='xing_ming_', max_length=200, blank=True, null=True)
    username = models.CharField(db_column='zhang_hao_', max_length=200, blank=True, null=True)
    faculty = models.CharField(db_column='suo_shu_dan_wei_', max_length=200, blank=True, null=True)
    back_school_transportation = models.CharField(db_column='ni_f_x_d_j_t_g_j_', max_length=200, blank=True, null=True)
    back_school_mode = models.CharField(db_column='ni_fan_x_d_l_j_', max_length=200, blank=True, null=True)
    back_school_path = models.TextField(db_column='fan_xiao_lu_jing_', blank=True, null=True)
    eating_habit = models.CharField(db_column='fan_x_h_y_c_x_g_', max_length=200, blank=True, null=True)


class COVID2019Test(models.Model):
    class Meta:
        managed = False
        app_label = 'ibps_business'
        db_table = 't_yqbmdsqyw'

    id_ = models.CharField(primary_key=True)
    username = models.CharField(db_column='xue_gong_hao_')
    test_time = models.DateField(db_column='jian_ce_ri_qi_')


class IbpsPartyUser(models.Model):
    id = models.CharField(db_column='ID_', primary_key=True, max_length=64)
    account = models.CharField(db_column='ACCOUNT_', max_length=64)
    password = models.CharField(db_column='PASSWORD_', max_length=1024)
    is_super = models.CharField(db_column='IS_SUPER_', max_length=1)
    data_check = models.CharField(db_column='DATA_CHECK_', max_length=1024)
    create_time = models.DateTimeField(db_column='CREATE_TIME_')
    update_time = models.DateTimeField(db_column='UPDATE_TIME_', blank=True, null=True)
    tenant_id = models.CharField(db_column='TENANT_ID_', max_length=64, blank=True, null=True)

    class Meta:
        managed = False
        app_label = 'ibps_platform'
        db_table = 'ibps_party_user'


class IbpsPartyUserRole(models.Model):
    id = models.CharField(db_column='ID_', primary_key=True, max_length=64)
    user_id = models.CharField(db_column='USER_ID_', max_length=64, blank=True, null=True)
    role_id = models.CharField(db_column='ROLE_ID_', max_length=64, blank=True, null=True)
    create_time = models.DateTimeField(db_column='CREATE_TIME_')

    class Meta:
        managed = False
        app_label = 'ibps_platform'
        db_table = 'ibps_party_user_role'


class XiaobanType(models.Model):
    username = models.CharField(max_length=30, verbose_name='用户学工号')
    type = models.CharField(max_length=20, verbose_name='校办提供的人员类型')

    class Meta:
        managed = False
        db_table = 'xiaoban_type'
        verbose_name = '校办提供的人员类型'
        verbose_name_plural = '校办提供的人员类型'


class DailySubmitInfo(models.Model):
    # 1-良好，2-发热，3-咳嗽，4-气促(2.0已弃用)，5-同时含义两种以上症状，6-头晕，7-腹泻，8-乏力；',
    HEALTHY, FEVER, COUGH, SHORTNESS_OF_BREATH, DIZZINESS, DIARRHEA, WEAK, OTHERS = 1, 2, 3, 4, 5, 6, 7, 8

    class Meta:
        managed = False
        db_table = 'daily_submit_info_new'
        verbose_name = '一日一报'
        verbose_name_plural = '一日一报'

    submit_time = models.DateField('填报日期', max_length=20)
    username = models.CharField('学工号', max_length=20)
    name = models.CharField('姓名', max_length=20)
    class_id = models.CharField('班级编号', max_length=20)
    class_name = models.CharField('班级名称', max_length=40)
    faculty_id = models.CharField('单位编号', max_length=20)
    faculty_name = models.CharField('单位名称', max_length=60)
    have_isolation_in_dg = models.IntegerField('是否在莞隔离医学观察')
    back_dg_transportation = models.IntegerField('返莞交通工具')
    finally_back_dg_transportation = models.IntegerField('最终返莞交通工具', db_column='finally_back_transportation')
    finally_back_time = models.CharField(max_length=60)
    campus = models.IntegerField('校区')
    current_country = models.IntegerField('所在国家')
    current_province = models.IntegerField('所在省份')
    current_city = models.IntegerField('所在城市')
    current_district = models.IntegerField('所在区县')
    HEALTH_SITUATION_CHOICE = (
        (1, '良好'),
        (2, '发热'),
        (3, '咳嗽'),
        (4, '气促'),
        (5, '同时含有两种以上症状'),
        (6, '头晕'),
        (7, '腹泻'),
        (8, '乏力'),
    )
    health_situation = models.IntegerField('健康状况', choices=HEALTH_SITUATION_CHOICE)
    have_gone_important_area = models.BooleanField("近14天是否到过中高风险地区")

    def get_city_name(self):
        if self.current_country != 142:
            return ProvinceCityNew.objects.filter(id=self.current_country).first().name
        else:
            city_name = ProvinceCityNew.objects.filter(id=self.current_city).first()
            city_name = str(city_name) if city_name else ''
            district_name = ProvinceCityNew.objects.filter(id=self.current_district).first()
            district_name = str(district_name) if district_name else ''
            return ''.join([city_name, district_name])

    @property
    def is_healthy(self):
        return self.health_situation == 1

    @staticmethod
    def get_last_report(username, submit_time):
        yesterday = datetime.strptime(submit_time, "%Y-%m-%d") + timedelta(days=-1)
        str_yesterday = yesterday.strftime("%Y-%m-%d")
        return DailySubmitInfo.objects.filter(username=username, submit_time=str_yesterday).first()

    @property
    def stay_in_outside_province(self):
        return self.current_province != 440000

    @property
    def have_gone_outside_province(self):
        if self.current_province != 440000:
            last_report = DailySubmitInfo.get_last_report(self.username, self.submit_time)
            if last_report and last_report.current_province == 440000:
                return True
        return False

    @property
    def leave_dongguan(self):
        if self.current_city not in (441900,):
            last_report = DailySubmitInfo.get_last_report(self.username, self.submit_time)
            if last_report:
                if last_report.current_city in (441900,):
                    return True
        return False

    @property
    def with_public_transport(self):
        TRANS, AIRPLANE, STEAMER, BUS, OTHERS = 0, 1, 2, 3, 5
        return self.finally_back_transportation in [TRANS, AIRPLANE, STEAMER, BUS, OTHERS]

    @property
    def continuous_unreport_days(self):
        today = date.today()
        n_days = cal_time(self.submit_time, today.strftime("%Y-%m-%d"))
        return n_days

    @property
    def stay_in_guangdong_period_of_leave(self):
        switch = True
        for item in DailySubmitInfo.objects.only('current_country', 'current_province', 'current_city').filter(username=self.username).order_by('-submit_time')[:14]:
            if switch and item.current_city in (441900,):
                continue
            switch = False

            if item.current_city not in (441900,) and item.current_province == 440000:
                continue
            elif item.current_province != 440000:
                return False
            elif item.current_city in (441900,):
                break
        return True

    # 实际返莞天数
    @property
    def finally_back_dongguan_days(self):
        n_days = 0
        res = DailySubmitInfo.objects.filter(username=self.username).order_by('-submit_time').filter(~Q(finally_back_time=None)).first()
        if res:
            import datetime
            finally_back_time = datetime.datetime.strptime(res.finally_back_time, '%Y-%m-%d')
            interval = datetime.datetime.now() - finally_back_time
            n_days = interval.days
        return n_days

    @property
    def is_has_been_in_guangdong(self):
        count = DailySubmitInfo.objects.filter(username=self.username, ).filter(~Q(current_province=440000)).count()
        return True if count == 0 else False

    # 返回广东天数
    @property
    def n_days_in_guangdong(self):
        today = date.today()
        n_days = 0
        for item in DailySubmitInfo.objects.filter(username=self.username).order_by('-submit_time'):
            submit_time = today - timedelta(days=n_days)
            if submit_time.strftime("%Y-%m-%d") == item.submit_time and item.current_country == 440000:
                n_days += 1
            else:
                break
        return n_days

    # 返回穗深莞惠天数
    @property
    def n_days_in_sui_shen_guan_hui(self):
        today = date.today()
        n_days = 0
        for item in DailySubmitInfo.objects.only('submit_time', 'current_city').filter(username=self.username).order_by('-submit_time'):
            submit_time = today - timedelta(days=n_days)
            if submit_time.strftime("%Y-%m-%d") == item.submit_time and item.current_city in (441900,):
                n_days += 1
            else:
                break
        return n_days

    # 返回东莞天数
    @property
    def n_days_in_dongguan(self):
        today = date.today()
        n_days = 0
        for item in DailySubmitInfo.objects.only('submit_time', 'current_city').filter(username=self.username).order_by('-submit_time'):
            submit_time = today - timedelta(days=n_days)
            if submit_time.strftime("%Y-%m-%d") == item.submit_time and item.current_city == 441900:
                n_days += 1
            else:
                break
        return n_days

    # 当前是否在莞隔离
    @property
    def is_isolation_in_dg(self):
        item = DailySubmitInfo.objects.only('have_isolation_in_dg').filter(username=self.username).order_by('-submit_time').first()
        if item and item.have_isolation_in_dg != 0:
            return True
        return False

    @property
    def pass_covid_2019_test(self):
        submit_time = datetime.strptime(self.submit_time, "%Y-%m-%d") + timedelta(days=-7)
        res = COVID2019Test.objects.filter(username=self.username, test_time__gte=submit_time)
        return True if res else False

    @property
    def have_never_been_to_risk_area(self):
        switch = True
        important_areas = []
        for item in ImportantArea.objects.only('region').filter(delete=0).all():
            important_areas.append(item.region)
        for item in DailySubmitInfo.objects.filter(username=self.username).order_by('-submit_time')[:14]:
            if switch and item.current_city in (441900,):
                continue
            switch = False

            if item.current_district in important_areas:
                return False
            elif item.current_city in (441900,):
                return True
            else:
                continue
        return True
    
    
    @property
    def have_gone_to_risk_area(self):
        important_provinces = []
        important_cities = []
        important_districts = []

        for item in ImportantCity.objects.only('region').filter(level=1, delete=0).all():
            important_provinces.append(item.region)

        for item in ImportantCity.objects.only('region').filter(level=2, delete=0).all():
            important_cities.append(item.region)

        for item in ImportantCity.objects.only('region').filter(level=3, delete=0).all():
            important_districts.append(item.region)

        if not self.current_province is None and str(self.current_province) in important_provinces:    
            return True
        elif not self.current_city is None and str(self.current_city) in important_cities:
            return True
        elif not self.current_district is None and str(self.current_district) in important_districts:
            return True
        else:
            return False


    @property
    def health_condition(self):
        today = date.today()
        n_days = 0
        for item in DailySubmitInfo.objects.filter(username=self.username).order_by('-submit_time'):
            submit_time = today - timedelta(days=n_days)
            if submit_time.strftime("%Y-%m-%d") == item.submit_time and item.health_situation == self.HEALTHY:
                n_days += 1
            else:
                break
        return n_days

    # 实际返莞交通方式
    @property
    def finally_back_transportation(self):
        back_dg_transportation = None
        res = DailySubmitInfo.objects.filter(~Q(finally_back_dg_transportation=None), username=self.username).order_by('-submit_time').first()
        if res:
            back_dg_transportation_map = {
                0: '火车',
                1: '飞机',
                2: '轮船',
                3: '长途公共巴士',
                4: '自驾',
                5: '其他'
            }
            back_dg_transportation = back_dg_transportation_map[res.finally_back_dg_transportation]
        return back_dg_transportation

    @property
    # 到访过的疫区
    def visited_risk_areas(self):
        risk_areas = set()
        for item in DailySubmitInfo.objects.filter(username=self.username).order_by('-submit_time'):
            obj = ImportantArea.objects.filter(region=item.current_district, delete=0).first()
            if obj:
                risk_areas.add(item.get_city_name())
        return '，'.join(risk_areas)

    # 离开疫区的时间
    @property
    def leave_risk_area_time(self):
        region = []
        for item in ImportantArea.objects.filter(delete=0).values('region'):
            region.append(item['region'])
        item = DailySubmitInfo.objects.filter(username=self.username).order_by('-submit_time').filter(~Q(current_country=142) | Q(current_district__in=region)).first()
        if item:
            leave_date = datetime.strptime(item.submit_time, "%Y-%m-%d") + timedelta(days=1)
            leave_date = leave_date.strftime("%Y-%m-%d")
            res = DailySubmitInfo.objects.filter(username=self.username).order_by('-submit_time').filter(submit_time=leave_date).first()

            return res.submit_time if res else None
        return None

    @staticmethod
    def access_check(username):
        queryset = DailySubmitInfo.objects.filter(username=username).order_by('-submit_time')

        # 是否一直在中国
        def is_has_been_in_china(queryset):
            count = queryset.filter(~Q(current_country=142)).count()
            return True if count == 0 else False

        # 是否一直在广东
        def is_has_been_in_guangdong(queryset):
            count = queryset.filter(~Q(current_province=440000)).count()
            return True if count == 0 else False

        # 是否一直在东莞
        def is_has_been_in_dongguan(queryset):
            count = queryset.filter(~Q(current_city=441900)).count()
            return True if count == 0 else False

        # 目前是否在重点地区
        def is_in_risk_area(queryset):
            item = queryset.first()
            if item:
                if item.current_country != 142:
                    return True
                if item.current_province == 420000:
                    return True
            return False

        # 目前所在地
        def get_current_city_name(queryset):
            item = queryset.first()
            return item.get_city_name() if item else None

        # 近十四天是否到过疫区
        def is_lasting_ever_been_to_risk_areas(queryset):
            for item in queryset.order_by('-submit_time')[:14]:
                if ImportantArea.objects.filter(region=item.current_district, delete=0).first():
                    return True
            return False

        # 是否到过疫区
        def is_ever_been_to_risk_areas(queryset):
            for item in queryset:
                if ImportantArea.objects.filter(region=item.current_district, delete=0).first():
                    return True
            return False

        # 到访过的疫区
        def visited_risk_areas(queryset):
            risk_areas = set()
            for item in queryset:
                obj = ImportantArea.objects.filter(region=item.current_district, delete=0).first()
                if obj:
                    risk_areas.add(item.get_city_name())
            return '，'.join(risk_areas)

        # 离开疫区的时间
        def leave_risk_area_time(queryset):
            region = []
            for item in ImportantArea.objects.filter(delete=0).values('region'):
                region.append(item['region'])
            item = queryset.filter(~Q(current_country=142) | Q(current_district__in=region)).first()
            if item:
                leave_date = datetime.strptime(item.submit_time, "%Y-%m-%d") + timedelta(days=1)
                leave_date = leave_date.strftime("%Y-%m-%d")
                res = queryset.filter(submit_time=leave_date).first()

                return res.submit_time if res else None
            return None

        # 当前是否在莞隔离
        def is_isolation_in_dg(queryset):
            item = queryset.first()
            if item and item.have_isolation_in_dg != 0:
                return True
            return False

        # 返回国内天数
        def n_days_in_china(queryset):
            today = date.today()
            n_days = 0
            for item in queryset:
                submit_time = today - timedelta(days=n_days)
                if submit_time.strftime("%Y-%m-%d") == item.submit_time and item.current_country == 142:
                    n_days += 1
                else:
                    break
            return n_days

        # 返回广东天数
        def n_days_in_guangdong(queryset):
            today = date.today()
            n_days = 0
            for item in queryset:
                submit_time = today - timedelta(days=n_days)
                if submit_time.strftime("%Y-%m-%d") == item.submit_time and item.current_country == 440000:
                    n_days += 1
                else:
                    break
            return n_days

        # 返回东莞天数
        def n_days_in_dongguan(queryset):
            today = date.today()
            n_days = 0
            for item in queryset:
                submit_time = today - timedelta(days=n_days)
                if submit_time.strftime("%Y-%m-%d") == item.submit_time and item.current_city == 441900:
                    n_days += 1
                else:
                    break
            return n_days

        # 连续打卡天数
        def continuous_report_days(queryset):
            today = date.today()
            n_days = 0
            for item in queryset:
                submit_time = today - timedelta(days=n_days)
                if submit_time.strftime("%Y-%m-%d") == item.submit_time:
                    n_days += 1
                else:
                    break
            return n_days

        # 连续未打卡天数
        def continuous_unreport_days(queryset):
            today = date.today()
            the_lasting_report = queryset.first()
            n_days = cal_time(today.strftime("%Y-%m-%d"), the_lasting_report.submit_time)
            return n_days

        # 连续身体健康天数
        def continuous_health_days(queryset):
            HEALTHY = 1
            today = date.today()
            n_days = 0
            for item in queryset:
                submit_time = today - timedelta(days=n_days)
                if submit_time.strftime("%Y-%m-%d") == item.submit_time and item.health_situation == HEALTHY:
                    n_days += 1
                else:
                    break
            return n_days

        # 实际返莞交通方式
        def finally_back_transportation(queryset):
            back_dg_transportation = None
            res = queryset.filter(~Q(finally_back_transportation=None)).first()
            if res:
                back_dg_transportation_map = {
                    0: '火车',
                    1: '飞机',
                    2: '轮船',
                    3: '长途公共巴士',
                    4: '自驾',
                    5: '其他'
                }
                back_dg_transportation = back_dg_transportation_map[res.finally_back_transportation]
            return back_dg_transportation

        # 是否使用公共交通工具返莞
        def use_public_transport(queryset):
            back_dg_transportation = None
            res = queryset.filter(~Q(finally_back_transportation=None)).first()
            if res:
                back_dg_transportation_map = {
                    0: '火车',
                    1: '飞机',
                    2: '轮船',
                    3: '长途公共巴士',
                    4: '自驾',
                    5: '其他'
                }
                back_dg_transportation = back_dg_transportation_map[res.finally_back_transportation]
            return True if back_dg_transportation in ['火车', '飞机', '轮船', '长途公共巴士', '其他'] else False

        # 实际返莞天数
        def finally_back_dongguan_days(queryset):
            n_days = 0
            res = queryset.filter(~Q(finally_back_time=None)).first()
            if res:
                import datetime
                finally_back_time = datetime.datetime.strptime(res.finally_back_time, '%Y-%m-%d')
                interval = datetime.datetime.now() - finally_back_time
                n_days = interval.days
            return n_days

        # 是否完成问卷
        def is_finished_questionnaire(username):
            res = ReturnSchoolQuestionnaire.objects.filter(username=username)
            return True if res else False

        def get_batch_info(username):
            NO_1 = '95807268980785152'
            NO_2 = '95807348165050368'
            NO_3 = '95807392796639232'
            user = IbpsPartyUser.objects.filter(account=username).first()
            userRole_1 = IbpsPartyUserRole.objects.filter(user_id=user.id, role_id=NO_1).first()
            userRole_2 = IbpsPartyUserRole.objects.filter(user_id=user.id, role_id=NO_2).first()
            userRole_3 = IbpsPartyUserRole.objects.filter(user_id=user.id, role_id=NO_3).first()

            if userRole_1:
                return 1
            elif userRole_2:
                return 2
            elif userRole_3:
                return 3

        res = dict()
        res["is_has_been_in_china"] = is_has_been_in_china(queryset)
        res["is_has_been_in_guangdong"] = is_has_been_in_guangdong(queryset)
        res["is_has_been_in_dongguan"] = is_has_been_in_dongguan(queryset)
        res["n_days_in_china"] = n_days_in_china(queryset)
        res["n_days_in_guangdong"] = n_days_in_guangdong(queryset)
        res["n_days_in_dongguan"] = n_days_in_dongguan(queryset)
        res["continuous_unreport_days"] = continuous_unreport_days(queryset)
        res["continuous_report_days"] = continuous_report_days(queryset)
        res["continuous_health_days"] = continuous_health_days(queryset)
        res["is_lasting_ever_been_to_risk_areas"] = is_lasting_ever_been_to_risk_areas(queryset)
        res["is_in_risk_area"] = is_in_risk_area(queryset)
        res["is_isolation_in_dg"] = is_isolation_in_dg(queryset)
        res["is_ever_been_to_risk_areas"] = is_ever_been_to_risk_areas(queryset)
        res["visited_risk_areas"] = visited_risk_areas(queryset)
        res["leave_risk_area_time"] = leave_risk_area_time(queryset)
        res["current_area"] = get_current_city_name(queryset)
        res["finally_back_transportation"] = finally_back_transportation(queryset)
        res["use_public_transport"] = use_public_transport(queryset)
        res["finally_back_dongguan_days"] = finally_back_dongguan_days(queryset)
        res["is_finished_questionnaire"] = is_finished_questionnaire(username)
        res["batch_number"] = get_batch_info(username)

        return res

    @staticmethod
    def teacher_access_check(username):
        queryset = DailySubmitInfo.objects.filter(username=username).order_by('-submit_time')

        # 连续打卡天数
        def continuous_report_days(queryset):
            today = date.today()
            n_days = 0
            for item in queryset:
                submit_time = today - timedelta(days=n_days)
                if submit_time.strftime("%Y-%m-%d") == item.submit_time:
                    n_days += 1
                else:
                    break
            return n_days

        # 连续未打卡天数
        def continuous_unreport_days(queryset):
            today = date.today()
            the_lasting_report = queryset.first()
            n_days = cal_time(today.strftime("%Y-%m-%d"), the_lasting_report.submit_time)
            return n_days

        # 连续身体健康天数
        def continuous_health_days(queryset):
            HEALTHY = 1
            today = date.today()
            n_days = 0
            for item in queryset:
                submit_time = today - timedelta(days=n_days)
                if submit_time.strftime("%Y-%m-%d") == item.submit_time and item.health_situation == HEALTHY:
                    n_days += 1
                else:
                    break
            return n_days

        # 实际返莞交通方式
        def finally_back_transportation(queryset):
            back_dg_transportation = None
            res = queryset.filter(~Q(finally_back_transportation=None)).first()
            if res:
                back_dg_transportation_map = {
                    0: '火车',
                    1: '飞机',
                    2: '轮船',
                    3: '长途公共巴士',
                    4: '自驾',
                    5: '其他'
                }
                back_dg_transportation = back_dg_transportation_map[res.finally_back_transportation]
            return back_dg_transportation

        # 是否使用公共交通工具返莞
        def use_public_transport(queryset):
            back_dg_transportation = None
            res = queryset.filter(~Q(finally_back_transportation=None)).first()
            if res:
                back_dg_transportation_map = {
                    0: '火车',
                    1: '飞机',
                    2: '轮船',
                    3: '长途公共巴士',
                    4: '自驾',
                    5: '其他'
                }
                back_dg_transportation = back_dg_transportation_map[res.finally_back_transportation]
            return True if back_dg_transportation in ['火车', '飞机', '轮船', '长途公共巴士', '其他'] else False

        # 返回广东天数
        def n_days_in_guangdong(queryset):
            today = date.today()
            n_days = 0
            for item in queryset:
                submit_time = today - timedelta(days=n_days)
                if submit_time.strftime("%Y-%m-%d") == item.submit_time and item.current_country == 440000:
                    n_days += 1
                else:
                    break
            return n_days

        # 实际返莞天数
        def finally_back_dongguan_days(queryset):
            n_days = 0
            res = queryset.filter(~Q(finally_back_time=None)).first()
            if res:
                import datetime
                finally_back_time = datetime.datetime.strptime(res.finally_back_time, '%Y-%m-%d')
                interval = datetime.datetime.now() - finally_back_time
                n_days = interval.days
            return n_days

        def have_gone_important_area(queryset):
            the_first_report = queryset.first()
            if the_first_report:
                return the_first_report.have_gone_important_area
            else:
                return False

        # 是否完成问卷
        def is_finished_coivd_2019_test(username):
            res = COVID2019Test.objects.filter(username=username, )
            return True if res else False

        res = dict()
        res['n_days_in_guangdong'] = n_days_in_guangdong(queryset)
        res['continuous_report_days'] = continuous_report_days(queryset)
        res['continuous_unreport_days'] = continuous_unreport_days(queryset)
        res['continuous_health_days'] = continuous_health_days(queryset)
        res['use_public_transport'] = use_public_transport(queryset)
        res['finally_back_dongguan_days'] = finally_back_dongguan_days(queryset)
        res['have_gone_important_area'] = have_gone_important_area(queryset)
        res['is_finished_coivd_2019_test'] = is_finished_coivd_2019_test(queryset)
        return res









